import os.path
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter


class ImageVerifyUtil(object):
    def __init__(self, x=140, y=40, length=4, size=30):
        """
        :param x: 图片宽度
        :param y: 图片高度
        :param length:
        :param size:
        """
        self.x = x
        self.y = y
        self.length = length
        self.size = size

    def random_str(self):
        """
        随机生成指定长度的字符串
        :return:
        """
        source = string.digits + string.ascii_letters
        return ''.join(random.sample(source, self.length))

    # 颜色干扰
    def random_color(self, start=0, end=255):
        """
        随机生成RGB颜色
        :param start:最小范围
        :param end:最大范围
        :return:
        """
        res = [random.randint(start, end) for i in range(3)]
        return tuple(res)

    # 干扰线
    def random_lines(self, draw):
        """
        :param draw:
        :return:
        """
        for i in range(self.length):
            lines = [(random.randint(0, self.x), random.randint(0, self.y)) for i in range(2)]
            draw.line(lines, fill=self.random_color(64, 200))

    # 干扰点
    def random_points(self, draw, rate):
        for x in range(self.x):
            for y in range(self.y):
                if random.randint(0, 100) <= rate:
                    draw.point((x, y), fill=self.random_color(64, 200))

    def verify_image(self):
        """
        生成组装图片
        :return:
        """
        # 创建画布
        image = Image.new("RGB", (self.x, self.y), (255, 255, 255))
        # 创建字体
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/KirangHaerang-Regular.ttf', self.size)
        # 画笔对象
        draw = ImageDraw.Draw(image)  # 在画布上创建画笔

        # 在画布上绘制干扰线和干扰点
        self.random_points(draw, 15)
        self.random_lines(draw)

        # 绘制答案
        code = self.random_str()
        for i in range(self.length):
            # 坐标，答案，字体，字体颜色
            draw.text((5 + 35 * i, random.randint(3, 6)), code[i], font=font, fill=self.random_color(64, 200))
        result = image.filter(ImageFilter.GaussianBlur(radius=1))
        return result,code

if __name__ == '__main__':
    image = ImageVerifyUtil()
    image,code=image.verify_image()
    with open('code.png','wb') as f:
        image.save(f)
    print(code)
